const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})

exports.main = async (event) => {
	try {
		const { articleid, title, content } = event
		const DB = cloud.database()

		const timeStamp = new Date().getTime()

		const newArticle = {
			last_modified_time: timeStamp,
			content,
			title,
		}
		await DB.collection('gn_article').doc(articleid).update({
			data: newArticle,
		})
		const getArticleInfo = await DB.collection('gn_article').doc(articleid).get()

		const spaceid = getArticleInfo.data.belong_space

		if (title) {
			const getHistoricalSpace = await DB.collection('gn_space').doc(spaceid).get()
			const spaceArticle = getHistoricalSpace.data.article
			const index = spaceArticle.findIndex((article) => article._id === articleid)
			spaceArticle[index].title = title
			await DB.collection('gn_space')
				.doc(spaceid)
				.update({
					data: {
						article: spaceArticle,
					},
				})
		}

		const getSpaceInfo = await DB.collection('gn_space').doc(spaceid).get()

		return {
			code: 0,
			msg: '创建成功',
			data: {
				space: getSpaceInfo.data,
				article: getArticleInfo.data,
			},
		}
	} catch (err) {
		throw err
	}
}
